import { Service } from 'egg';
import { v4 as uuidv4 } from 'uuid';

class JobPositionService extends Service {
  async findListByUuid(uuid: string) {
    const tableData = await this.ctx.model.JobPosition.findAll({
      attributes: ['id', 'uuid', 'name'],
      include: [
        {
          model: this.ctx.model.Questionnaire,
          where: { uuid },
        },
      ],
    });
    return tableData;
  }

  async delete(
    uuid: string,
    questionnaireUuid: string
  ) {
    const removedResult = await this.ctx.model.JobPosition.destroy(
      { where: { uuid } }
    );
    // TODO: 判断该问卷下的list是否为空
    const optionCount = await this.ctx.model.Questionnaire.count({
      include: [
        {
          model: this.ctx.model.JobPosition,
          attributes: ['uuid', 'name'],
          required: true,
          as: 'jobPosition'
        },
      ],
      where: { uuid: questionnaireUuid },
    });
    if (optionCount === 0) {
      // 直接设置对应的visable为空
      await this.ctx.model.Questionnaire.update({
        jobPositionVisible: 0,
      }, { where: { uuid: questionnaireUuid } });
      return false;
    }
    return removedResult;
  }

  async create(questionnaireUuid: string, name: string) {
    const { ctx } = this;

    const result = await ctx.model.transaction(async (t) => {
      const foundQuestionnaire = await ctx.model.Questionnaire.findOne({
        where: { uuid: questionnaireUuid }
      }, { transaction: t });

      if (!foundQuestionnaire) {
        return undefined;
      }

      const { id } = foundQuestionnaire;

      const isExist = await ctx.model.JobPosition.findOne({
        where: { name, fk_questionnaire: id }
      }, { transaction: t });

      if (isExist) {
        return undefined;
      }

      const createResult = await this.ctx.model.JobPosition.create(
        {
          uuid: uuidv4(),
          name,
          fk_questionnaire: id,
        }, { transaction: t }
      );

      return createResult;
    });

    return result;
  }
}

module.exports = JobPositionService;
